package com.ljkj.cordial.lengthtcpheartbeat;


import com.lanjiu.lib.communication.IMSConfig;
import com.lanjiu.pro.business.BusinessProtocolMessageStandard;
import com.nic.view.util.JLog;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

@ChannelHandler.Sharable
public class HeartBeatEventHandler extends ChannelInboundHandlerAdapter {
    private static String TAG = OnEventMessageListener.TAG;

    private OnEventMessageListener onEventMessageListener;
    private OnConnectStateCallback onConnectStateCallback;
//    private Vector<BusinessProtocolMessageStandard.CheckUnifiedEntranceMessage> vector = new Vector<>();

    //
    public HeartBeatEventHandler(OnEventMessageListener onEventMessageListener, OnConnectStateCallback onConnectStateCallback) {
        this.onEventMessageListener = onEventMessageListener;
        this.onConnectStateCallback = onConnectStateCallback;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        JLog.d(OnEventMessageListener.TAG, "-长连接 active-" + ctx.channel().id().toString());
        onEventMessageListener.setCtx(ctx, onConnectStateCallback);
        onEventMessageListener.send(onEventMessageListener.getEmptyMsg(IMSConfig.HEART_PACKAGE_PHONE));
//        JLog.d(OnEventMessageListener.TAG, "active channelId=" + ctx.channel().id().toString());
    }

    @SuppressWarnings("unchecked")
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        super.channelRead(ctx, msg);
//        JLog.d(OnEventMessageListener.TAG, "read channelId=" + ctx.channel().id().toString());
        BusinessProtocolMessageStandard.CheckUnifiedEntranceMessage result = (BusinessProtocolMessageStandard.CheckUnifiedEntranceMessage) msg;
        try {
            if (result.getUnifiedEntranceMessage() == null || result.getUnifiedEntranceMessage().getHead() == null) {
                onConnectStateCallback.onFailed("empty");
                return;
            }
            onEventMessageListener.receiveMsg(result);
        } catch (Exception e) {
//            e.printStackTrace();
//            try {
//                onConnectStateCallback.onFailed(result.getUnifiedEntranceMessage().getDataType());
//            } catch (Exception e1) {
//                e1.printStackTrace();
//            }
            ctx.fireChannelRead(msg);
        }
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        JLog.e(OnEventMessageListener.TAG, "-长连接 inactive-");
//        !onEventMessageListener.isFailingWriting() ||
        if (!onEventMessageListener.isForceExit() && !onEventMessageListener.isReConnecting()) {
            if (onConnectStateCallback != null) {
                onConnectStateCallback.onDoConnect(ctx);
            }
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        JLog.e(OnEventMessageListener.TAG, "-长连接 exceptionCaught-");
        ctx.close();
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleState state = ((IdleStateEvent) evt).state();
//            if (state == IdleState.READER_IDLE) {
//                JLog.w(TAG, "read overtime");
////                onEventMessageListener.setOverTimeLli(ctx.channel());
//            } else
                if (state == IdleState.WRITER_IDLE) {
                JLog.w(TAG, "write overtime");
                onEventMessageListener.send(onEventMessageListener.getEmptyMsg(IMSConfig.HEART_PACKAGE_PHONE));
            }
//                else {
//                JLog.w(TAG, "all overtime");
//            }
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }
}

